﻿using AutoMapper.Configuration;
using Identity.API.IdentityConfig;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Identity.API.Data
{
    public class ConfigurationDbContextSeeds
    {
        public static async Task SeedAsync(ConfigurationDbContext configDbContext)
        {
            await configDbContext.Database.MigrateAsync();

            if (!await configDbContext.ApiScopes.AnyAsync())
            {

                foreach (var apiScope in Config.GetApiScopes)
                {
                    await configDbContext.ApiScopes.AddAsync(apiScope.ToEntity());
                }
                await configDbContext.SaveChangesAsync();
            }

            if (!await configDbContext.Clients.AnyAsync())
            {
                foreach (var client in Config.GetClients)
                {
                    await configDbContext.Clients.AddAsync(client.ToEntity());
                }
                await configDbContext.SaveChangesAsync();
            }

            if (!await configDbContext.IdentityResources.AnyAsync())
            {
                foreach (var resource in Config.GetIdentityResources)
                {
                    await configDbContext.IdentityResources.AddAsync(resource.ToEntity());
                }
                await configDbContext.SaveChangesAsync();
            }

            if (!await configDbContext.ApiResources.AnyAsync())
            {
                foreach (var resource in Config.GetApiResources)
                {
                    await configDbContext.ApiResources.AddAsync(resource.ToEntity());
                }
                await configDbContext.SaveChangesAsync();
            }
        }
    }
}
